package com.zf.yichat.controller;


import com.zf.yichat.config.utils.MenuUtils;
import com.zf.yichat.model.SysMenu;
import com.zf.yichat.service.SysMenuService;
import com.zf.yichat.utils.response.FsResponse;
import com.zf.yichat.utils.response.FsResponseGen;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.io.BufferedReader;
import java.io.Closeable;
import java.io.File;
import java.io.InputStreamReader;
import java.util.List;
import java.util.stream.Collectors;

@Controller
public class IndexController extends BaseController {

    @Autowired
    private SysMenuService menuService;

    @RequestMapping("/")
    public String index() {
//
//        // 校验是否已登录
//        HttpSession session = getRequest().getSession();
//        if (session != null) {
//            Object user = session.getAttribute("user");
//            if (user == null) {
//                return "login/login";
//            }
//        }

        List<SysMenu> menuList = menuService.selectListByUserId(getUserId());
        if (!isOperate()) {
            menuList = menuList.stream().filter(v -> !StringUtils.equals(v.getName(), "提现审核")).collect(Collectors.toList());
        }
        getRequest().setAttribute("menuList", MenuUtils.generateMenuData(menuList));
        return "index";
    }

    @RequestMapping("index/main")
    public String main() {
        return "welcome";
    }


    @ResponseBody
    @RequestMapping("login/count")
    public FsResponse onlineCount() {


        return FsResponseGen.successData(execCmd("netstat -nat | grep -i \"5222\" | wc -l", null));

    }


    /**
     * 执行系统命令, 返回执行结果
     *
     * @param cmd 需要执行的命令
     * @param dir 执行命令的子进程的工作目录, null 表示和当前主进程工作目录相同
     */
    public static String execCmd(String cmd, File dir) {
        StringBuilder result = new StringBuilder();

        Process process = null;
        BufferedReader bufrIn = null;
        BufferedReader bufrError = null;

        try {
            String[] commond = {"/bin/s" +
                    "" +
                    "h", "-c", cmd};
// 执行命令, 返回一个子进程对象（命令在子进程中执行）
            process = Runtime.getRuntime().exec(commond, null, dir);

// 方法阻塞, 等待命令执行完成（成功会返回0）
            process.waitFor();

// 获取命令执行结果, 有两个结果: 正常的输出 和 错误的输出（PS: 子进程的输出就是主进程的输入）
            bufrIn = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8"));
            bufrError = new BufferedReader(new InputStreamReader(process.getErrorStream(), "UTF-8"));

// 读取输出
            String line = null;
            while ((line = bufrIn.readLine()) != null) {
                result.append(line);
            }
            while ((line = bufrError.readLine()) != null) {
                result.append(line).append('\n');
            }

        } catch (Exception e) {

        } finally {
            closeStream(bufrIn);
            closeStream(bufrError);

// 销毁子进程
            if (process != null) {
                process.destroy();
            }
        }

// 返回执行结果
        return result.toString().trim();
    }

    private static void closeStream(Closeable stream) {
        if (stream != null) {
            try {
                stream.close();
            } catch (Exception e) {
// nothing
            }
        }
    }


}
